package com.chess.dwr;

import java.util.Collection;

import javax.servlet.ServletException;

import org.directwebremoting.Browser;
import org.directwebremoting.ScriptBuffer;
import org.directwebremoting.ScriptSession;
import org.directwebremoting.ScriptSessionFilter;
import org.directwebremoting.WebContextFactory;

import com.chess.listener.DWRScriptSessionListener;
import com.chess.manager.DwrScriptSessionManagerUtil;

public class MessagePush {

	public void onPageLoad(final String userId) {
		// 获取当前的ScriptSession
		ScriptSession scriptSession = WebContextFactory.get().getScriptSession();
		scriptSession.setAttribute("userId", userId);
		DwrScriptSessionManagerUtil dwrScriptSessionManagerUtil = new DwrScriptSessionManagerUtil();
        try {
               dwrScriptSessionManagerUtil.init();
        } catch (ServletException e) {
               e.printStackTrace();
        }
	}

//	public void send(final String userId, final String col, final String row) {
//		// 过滤器
//		ScriptSessionFilter filter = new ScriptSessionFilter() {
//			public boolean match(ScriptSession session) {
//				if (session.getAttribute("userId") == null)
//					return false;
//				else
//					return (session.getAttribute("userId")).equals(userId);
//			}
//		};
//		Runnable run = new Runnable() {
//			private ScriptBuffer script = new ScriptBuffer();
//
//			public void run() {
//				// 设置要调用的 js及参数
//				script.appendCall("show", col, row);
//				// 得到所有ScriptSession
//				Collection<ScriptSession> sessions = DWRScriptSessionListener
//						.getScriptSessions();
//				// 遍历每一个ScriptSession
//				for (ScriptSession scriptSession : sessions) {
//					scriptSession.addScript(script);
//				}
//			}
//		};
//		// 执行推送
//		Browser.withAllSessionsFiltered(filter, run); // 注意这里调用了有filter功能的方法
//	}

	public void send(final String userId, final String col, final String row) {
		Browser.withAllSessionsFiltered(new ScriptSessionFilter() {
			public boolean match(ScriptSession session) {
				if (session.getAttribute("userId") == null)
					return false;
				else
					return (session.getAttribute("userId")).equals(userId);
			}
		}, new Runnable() {
			private ScriptBuffer script = new ScriptBuffer();

			public void run() {
				script.appendCall("show", col, row);
				Collection<ScriptSession> sessions = Browser
						.getTargetSessions();
				for (ScriptSession scriptSession : sessions) {
					scriptSession.addScript(script);
				}
			}
		});

	}
}
